﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Bots;
using System.Configuration;

namespace Sample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private LinkSearcher searcher;
        protected override void OnLoad(EventArgs e)
        {
            searcher = new LinkSearcher();            
            base.OnLoad(e);
        }

        private void searchBox_Click(object sender, EventArgs e)
        {
            DomainSet domainSet = null;
            if(!string.IsNullOrEmpty(keywordBox.Text.Trim())){
                domainSet = searcher.Search(new Bots.Search.QueryTerm("Link", keywordBox.Text.Trim()), 1, 50);
                dataGridView1.DataSource = Array.ConvertAll(domainSet.DomainObjects, new Converter<DomainObject,Link>(ToLink));
            }
        }

        private Link ToLink(DomainObject obj) {
            return obj as Link;
        }

        private void addItemBox_Click(object sender, EventArgs e)
        {
            AddForm f1 = new AddForm();
            f1.ShowDialog();
        }     

        private void updateBtn_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                long linkid = Convert.ToInt64(dataGridView1.SelectedRows[0].Cells[6].FormattedValue);
                AddForm f1 = new AddForm(linkid);
                f1.ShowDialog();
            }
        }

        private void delBtn_Click(object sender, EventArgs e)
        {
            if(dataGridView1.SelectedRows.Count > 0){
                long linkid = Convert.ToInt64(dataGridView1.SelectedRows[0].Cells[6].FormattedValue);
                DeleteIndex(linkid);
            }
        }

        private void DeleteIndex(long linkId) {
            SqlConnection connection = null;
            try
            {
                //at first delete index 
                Link link = new Link(linkId);
                link.ObjectStatue = Bots.ObjectStatue.Delete;
                Bots.Index.IncIndexManager.IncIndexAdd(link);

                connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
                SqlCommand cmd = new SqlCommand("DeleteLink", connection);
                connection.Open();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@LinkID", SqlDbType.BigInt).Value = linkId;
                int ret = cmd.ExecuteNonQuery();

            }
            finally
            {
                if (connection != null)
                {
                    connection.Close();
                }
            }
        }

        
        
    }
}
